var db      = require('../models');
var _       = require('underscore');

exports.list =  function(req, res){
  console.log("note.list", req.body);
  db.Note.findAll({where: {user_id :req.user.id}}).success(function(notes) {
    console.log("got notes", notes);
    res.json(200, {notes:notes});
  });
};

exports.create =  function(req, res){
  console.log("note.create", req.body);
  db.Note.create({ 
    user_id:         req.user.id, 
    conversation_id: req.body.conversation_id,
    location_id:     req.body.location_id,
    text:            req.body.text,
    added:           new Date()
  })
  .success(function(note) {
    res.send(200);
  })
  .error(function(err) {
    res.json(400, {message:'Error while creating note'});
  });
};

exports.get =  function(req, res){
  console.log("note.get", req.query, req.params);
  
  db.Note.find(req.params.id).success(function(note) {
    if (note.user_id == req.user.id) {
      res.json(200, {note:note});
    }
    else {
      res.json(400,{message: "Unauthorized"});
    }
  });
};

exports.update =  function(req, res){
  console.log("note.update", req.query, req.params, req.body);
  
  db.Note.find(req.params.id).success(function(note) {
    if (note.user_id == req.user.id) {
      note.updateAttributes(req.body, _.keys(req.body)).success(function() {
        res.json(200, {note:note});  
      });
    }
    else {
      res.json(400,{message: "Unauthorized"});
    }
  });
};

exports.remove =  function(req, res){
    db.Note.find(req.params.id).success(function(note) {
    if (note.user_id == req.user.id) {
      note.destroy().success(function() {
        res.json(200, {note:note});  
      });
    }
    else {
      res.json(400,{message: "Unauthorized"});
    }
  });
};
